import 'package:flutter/material.dart';
import 'package:t2app/src/Config.dart';
import 'package:t2app/src/common/AppData.dart';
import 'package:t2app/src/common/Tool.dart';
import 'package:t2app/src/util/log_util.dart';
import 'package:t2app/src/view/login/Login.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:fluwx/fluwx.dart';

import '../../entity/User.dart';
import '../../util/http_request.dart';


class LoginIndexView extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginIndexView> {
  bool _isAgreed = false;
  Fluwx _fluwx = Fluwx();

  @override
  initState() {
    super.initState();
   _fluwxInit();
  }

  _fluwxInit(){
    //微信appid
    _fluwx.registerApi(
      appId: Config.WEI_XIN['appId']??"" ,
      doOnAndroid: true,
      doOnIOS: true,
      universalLink: Config.WEI_XIN['universalLink']??"" ,
    ).then((bool){
      LogUtil.p("fluwx 注册结果:" + bool.toString());
      _fluwx.addSubscriber((response) {
        LogUtil.p("fluwx 监听响应:" + response.toString());
        if(response is WeChatAuthResponse) {
           String? code = response.code;
           if(code == null) {
             Tool.EasyLoading_Error("微信登录失败,请稍后再试");
             return;
           }
             HttpRequest().request(
               Config.DOMAIN + "/user/weixin_login",
               method: HttpRequestMethod.POST,
               data: {
                 "code": code,
               },
               success: (result) {
                 // LogUtil.p(result);
                 //缓存
                 User user = User.fromMap(result["data"]);
                 AppData.user = user;
                 user.putStorage();
                 Tool.EasyLoading_Success("注册成功");
                 //跳转
                 Navigator.of(context).pop(true);
               },
             );
           }
        }
      );
    });
  }

  void _weixinLogin() async {

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // 背景渐变色
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.purple[200]!,
                  Colors.blue[200]!,
                ],
              ),
            ),
          ),
          // 内容区域
          Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // 顶部导航
                SafeArea(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      IconButton(
                        icon: Icon(Icons.arrow_back),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                      TextButton(
                        onPressed: () {
                          // 在这里添加跳转逻辑，例如跳转到另一个页面
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => LoginView(),
                            ),
                          );
                        },
                        child: Text(
                          '账号登录',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                // 中间内容
                Column(
                  children: [
                    Image.asset(
                      Config.LOGO_LOCAL, // 替换成实际的logo图片路径
                      width: 120,
                      height: 120,
                    ),
                    SizedBox(height: 20),
                    Text(
                      '塑造数字分身，绽放无限自由(标题)',
                      style: TextStyle(
                        color:  Config.THEME.primaryColorDark,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(height: 10),
                    Text(
                      '一键分身让创作更自由（描述）',
                      style: TextStyle(
                        fontSize: 14,
                        color: Config.THEME.primaryColor,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
                // 底部登录区域
                Column(
                  children: [
                    SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton.icon(
                        onPressed: () {
                          if (!_isAgreed) {
                            Tool.showTipsDialog(context, "请先阅读并同意用户协议和隐私政策");
                            return;
                          }
                          // 微信登录逻辑
                          // 检查微信是否安装
                          _fluwx.isWeChatInstalled.then((isInstalled) {
                            LogUtil.p("fluwx检测安装微信结果："+ isInstalled.toString());
                            if (isInstalled) {
                              // 发起微信登录请求
                              _fluwx.authBy(
                                which: NormalAuth(
                                  scope: "snsapi_userinfo",
                                  state: "wechat_login")
                              ).then((bool){
                                LogUtil.p("fluwx:auth:bool:"+ bool.toString());
                              }, onError: (error) {
                                 LogUtil.p("fluwx:auth:error:"+ error.toString());
                                 Tool.showTipsDialog(context, '微信登录授权失败/'+error.toString());
                              });
                            } else {
                              Tool.showTipsDialog(context, '未安装微信，无法进行微信登录');
                            }
                          });
                        },
                        label: Text('微信登录'),
                        style: ElevatedButton.styleFrom(
                          foregroundColor: Colors.cyan,
                          padding: EdgeInsets.symmetric(
                              vertical: 15, horizontal: 30),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(30),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 10),
                    Row(
                      children: [
                        Checkbox(
                          value: _isAgreed,
                          onChanged: (value) {
                            setState(() {
                              _isAgreed = value!;
                            });
                          },
                        ),
                        Text(
                          '我已阅读并接受',
                          style: TextStyle(fontSize: 14),
                        ),
                        GestureDetector(
                          onTap: () => {
                              Navigator.pushNamed(
                                context,
                                'webview',
                                arguments: {
                                  'url': Config.DOMAIN + "/agreement/user_agreement",
                                  'title': '用户协议',
                                },
                              )
                          },
                          child: Text(
                            '《用户协议》',
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.blue,
                            ),
                          ),
                        ),
                        Text(
                          '和',
                          style: TextStyle(fontSize: 14),
                        ),
                        GestureDetector(
                          onTap: () => {
                            Navigator.pushNamed(
                              context,
                              'webview',
                              arguments: {
                                'url': Config.DOMAIN + "/agreement/privacy_agreement",
                                'title': '隐私政策',
                              },
                            )
                          },
                          child: Text(
                            '《隐私政策》',
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.blue,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}